<template>
  <div class="zl-textarea" ref="parentEl">
    <textarea
      ref="inputField"
      :placeholder="showPlaceHolder ? '输入你的笔记,支持粘贴截图笔记' : ''"
      class="dynamic-textarea"
      v-model="fieldValue"
      :id="id ? id : 'r' + index"
      :style="{ minHeight: rows * 20 + 'px' }"
      @paste="handlePaste($event)"
      @input="handleInput($event)"
      :readonly="disabled || readonly ? true : false"
      :disbaled="disabled ? true : false"
      :class="{ 'textarea-disabled': disabled }"
    ></textarea>

    <textarea
      class="dynamic-textarea copy-field"
      style="height: 1px;min-height: unset;visibility: hidden;position: relative;margin-top:-1px;"
      ref="copyField"
      placeholder="输入你的笔记,支持粘贴截图笔记"
      v-model="fieldValue"
    ></textarea>
  </div>
</template>

<script>
export default {
  name: 'zlTextarea',

  data() {
    return {
      fieldValue: ''
    }
  },
  props: {
    // 记录当前索引
    index: {
      type: Number,
      default: 0
    },
    // 文本框内容
    content: {
      type: String,
      default: null
    },
    // 传入id
    id: {
      type: String,
      default: ''
    },
    rows: {
      type: Number,
      default: 1
    },
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showPlaceHolder: {
      type: Boolean,
      default: true
    }
  },

  methods: {
    // 处理粘贴
    handlePaste(e) {
      this.$emit('paste', e)
    },
    // 处理输入
    handleInput(e) {
      // console.log(e.target.value);
      this.$emit('update:content', e.target.value)
      this.$emit('input', e)
    },
    handleInput2(val) {
      // console.log(val, 'val')
      this.$emit('update:content', val)
    },
    computeTextareaHeight(height) {
      let inputBox = this.$refs.inputField
      this.$nextTick(() => {
        inputBox.style.height = height + 'px'
      })
    },
    // 动态获取当前文本在当前输入框中的实际高度
    dynamicCalcTextareaHeight(newVal) {
      if (!newVal) return 0
      let h = this.$refs.copyField.scrollHeight
      return h
    }
  },
  watch: {
    content: {
      handler(val) {
        this.fieldValue = val
        if (typeof window !== 'undefined') {
          // 动态计算textarea的高度
          this.$nextTick(() => {
            let h = this.dynamicCalcTextareaHeight(val)
            this.computeTextareaHeight(h)
          })
        }
      },
      // 此处只做值的监听使用，只在前端执行
      immediate: true
    }
  }
}
</script>
<style scoped>
.zl-textarea {
  position: relative;
  width: 100%;
}
.dynamic-textarea {
  display: block;
  border: none;
  outline: 0;
  width: 100%;
  line-height: 20px;
  min-height: 20px;
  background-color: transparent;
  color: #b3b3b3;
  font-size: 14px;
  font-family: 'Microsoft YaHei';
  resize: none;
}
.textarea-disabled {
  cursor: not-allowed;
}
.dynamic-textarea::-webkit-scrollbar {
  display: none;
}
</style>
